package testes;

import java.io.FileNotFoundException;
import java.net.SocketException;
import java.util.StringTokenizer;

import base.transporte.FilePackager;
import base.transporte.SRPacket;
import base.transporte.SRSocket;
import base.transporte.SRWelcomer;



public class TesteServerMulti {
	private static class threadArquivo implements Runnable{

		SRSocket conector;
		
		public threadArquivo(SRSocket conector) {
			this.conector = conector;
		}
		
		@Override
		public void run() {
			SRPacket pacote = null;
			boolean iniciarTransferencia = false;
			
			String fileName = null;
			while (!iniciarTransferencia) {
				pacote = conector.receberPacote();
				String cmd = new String(pacote.getData());
				StringTokenizer tokenizedLine = new StringTokenizer(cmd);
				if (tokenizedLine.nextToken().equals("GET")) {
					fileName = tokenizedLine.nextToken();
					System.out.println("Cliente baixando " + fileName);
					iniciarTransferencia = true;
				}

			}
			
			FilePackager fileIn = null;
			try {
				fileIn = new FilePackager("C:/temp/metodo.avi");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			long time = System.currentTimeMillis();


			while(!fileIn.isEOF())
			{
				pacote = (fileIn.getNextPacket());
				conector.enviarPacote(pacote);
				if(System.currentTimeMillis() > time + 1000)
				{
					time = System.currentTimeMillis();
					System.out.println(conector.getVelUploadFormatada());
				}
			}
			

			System.out.println("Acabou!!!!!!!!!!!!!!!!!!!!!!!!!");
			
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		SRWelcomer welcomerskt = null;
		try {
			welcomerskt = new SRWelcomer(60000, "UpadorArquivo");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Thread welcomerThread = new Thread(welcomerskt);
		welcomerThread.setPriority(Thread.MIN_PRIORITY);
		welcomerThread.start();

		while (true) {
			
			SRSocket conector = welcomerskt.accept();
			Thread upador = new Thread(new threadArquivo(conector));
			upador.setPriority(Thread.MAX_PRIORITY);
			upador.start();
		}
		
		
		
	}
}
